//
//  ImageBrowserView.m
//  etionUI
//
//  Created by WangJian on 14-2-17.
//  Copyright (c) 2014年 GuangZhouXuanWu. All rights reserved.
//

#import "ImageBrowserView.h"
#import "ImageAnimatedShowView.h"
#import "CircleButton.h"

#define MARGIN 15
#define BTN_RADIUS 16

@implementation CImageBrowserLayout

- (id)init
{
    self = [super init];
    if (self)
    {
        self.itemSize = CGSizeMake([UIApplication sharedApplication].keyWindow.size.width, [UIApplication sharedApplication].keyWindow.size.height);
        self.minimumLineSpacing = 0;
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
    self.collectionView.contentSize = CGSizeMake([self.collectionView numberOfItemsInSection:0]*(self.itemSize.width), self.itemSize.height);
}

- (NSArray *)visibleAttributes
{
    CGRect visibleRect;
    visibleRect.origin = self.collectionView.contentOffset;
    visibleRect.size = self.collectionView.bounds.size;
    return [super layoutAttributesForElementsInRect:visibleRect];
}

@end

@implementation CImageBrowserButtonItem

+ (CImageBrowserButtonItem *)itemWithTitle:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage
{
    return [[[CImageBrowserButtonItem alloc] initWithTitle:title image:image selectedImage:selectedImage] autorelease];
}

- (CImageBrowserButtonItem *)initWithTitle:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage
{
    if (self = [super init])
    {
        self.title = title;
        self.image = image;
        self.selectedImage = selectedImage;
    }
    return self;
}

- (void)dealloc
{
    [_title release];
    [_image release];
    [_selectedImage release];
    [super dealloc];
}

@end


@interface CImageBrowserView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) CImageAnimatedShowView *showView;

@property (nonatomic, retain) CCircleButton *backBtn;
@property (nonatomic, retain) NSMutableArray *optionBtns;

@end

@implementation CImageBrowserView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.imageBrowserView = [[[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:[[[CImageBrowserLayout alloc] init] autorelease]] autorelease];
        self.imageBrowserView.dataSource = self;
        self.imageBrowserView.delegate = self;
        self.imageBrowserView.pagingEnabled = YES;
        self.imageBrowserView.backgroundColor = [UIColor clearColor];
        [self.imageBrowserView registerClass:[CImageBrowserViewCell class] forCellWithReuseIdentifier:@"imageCell"];
        
        self.showView = [[[CImageAnimatedShowView alloc] initWithFrame:self.bounds] autorelease];
        [self addSubview:self.showView];
        
        self.imageBrowserView.frame = CGRectMake(0, 0, self.width, self.height);
        [self.showView.contentView addSubview:self.imageBrowserView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureResponse:)];
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.numberOfTouchesRequired = 1;
        [self.imageBrowserView addGestureRecognizer:tapGesture];
        [tapGesture release];
        
        self.backBtn = [[[CCircleButton alloc] initWithFrame:CGRectMake(MARGIN, -2*BTN_RADIUS, 2*BTN_RADIUS, 2*BTN_RADIUS) normalImage:[UIImage imageNamed:@"pb_backarrow_normal"] highlightedImage:[UIImage imageNamed:@"pb_backarrow_selected"]] autorelease];
        self.backBtn.hidden = YES;
        [self.backBtn addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.backBtn];
        
        self.optionBtns = [NSMutableArray array];
        self.showBtns = NO;
    }
    return self;
}

- (void)dealloc
{
    [_buttonItems release];
    [_optionBtns release];
    [_backBtn release];
    
    [_imageBrowserView release];
    [_showView release];
    [super dealloc];
}

#pragma mark - deal button item

- (CGFloat)buttonTop
{
    if (self.optionBtns.count > 0)
    {
        return [[self.optionBtns objectAtIndex:0] top];
    }
    return 0;
}

- (void)setButtonItems:(NSArray *)buttonItems
{
    NSArray *tmp = [buttonItems retain];
    [_buttonItems release];
    _buttonItems = tmp;
    
    self.backBtn.hidden = buttonItems.count == 0;
    for (CCircleButton *btn in self.optionBtns)
    {
        [btn removeFromSuperview];
    }
    [self.optionBtns removeAllObjects];
    NSInteger btnAreaW = self.width/(buttonItems.count+1);
    NSInteger startX = btnAreaW/2;
    for (NSUInteger i=0; i<self.buttonItems.count; i++)
    {
        CImageBrowserButtonItem *btnItem = [self.buttonItems objectAtIndex:i];
        CCircleButton *btn = [[[CCircleButton alloc] initWithNormalImage:btnItem.image highlightedImage:btnItem.selectedImage radius:BTN_RADIUS title:btnItem.title titlePosition:ECircleButtonTitlePositionBottom] autorelease];
        btn.tag = i;
        [btn addTarget:self action:@selector(operationButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(startX + btnAreaW*i+(btnAreaW-btn.width)/2, self.height, btn.width, btn.height);
        [self.optionBtns addObject:btn];
        [self addSubview:btn];
    }
}

- (void)showButtonItemsAnimated:(BOOL)animated complete:(void (^)(BOOL finished))complete
{
    self.showBtns = YES;
    [UIView animateWithDuration:animated?0.25:0.0 animations:^
    {
        for (NSUInteger i=0; i<self.optionBtns.count; i++)
        {
            CCircleButton *btn = [self.optionBtns objectAtIndex:i];
            btn.top = self.height-btn.height-MARGIN;
        }
        self.backBtn.top = MARGIN;
    } completion:^(BOOL finished)
    {
        complete(finished);
    }];
}

- (void)hideButtonItemsAnimated:(BOOL)animated complete:(void (^)(BOOL finished))complete
{
    self.showBtns = NO;
    [UIView animateWithDuration:animated?0.25:0.0 animations:^
    {
        for (NSUInteger i=0; i<self.optionBtns.count; i++)
        {
            CCircleButton *btn = [self.optionBtns objectAtIndex:i];
            btn.top = self.height;
        }
        self.backBtn.top = -self.backBtn.height;
    } completion:^(BOOL finished)
    {
        complete(finished);
    }];
}

- (void)backButtonClicked:(id)sender
{
    CImageBrowserViewCell *cell = (CImageBrowserViewCell *)[self.imageBrowserView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.curImageIndex inSection:0]];
    [cell setImageZoomScale:1.0 animated:YES complete:^
    {
        [self.delegate imageBrowserViewNeedGetBack:self];
    }];
}

- (void)operationButtonClicked:(CCircleButton *)btn
{
    if ([self.delegate respondsToSelector:@selector(imageBrowserView:didClickButtonItemAtIndex:)])
    {
        [self.delegate imageBrowserView:self didClickButtonItemAtIndex:btn.tag];
    }
}

- (void)tapGestureResponse:(UITapGestureRecognizer *)tapgesture
{
    if (self.buttonItems.count > 0)
    {
        if (self.showBtns == YES)
        {
            [self hideButtonItemsAnimated:YES complete:^(BOOL finished) {}];
        }
        else
        {
            [self showButtonItemsAnimated:YES complete:^(BOOL finished) {}];
        }
    }
    else
    {
        [self backButtonClicked:nil];
    }
}

#pragma mark - edit

- (void)didMoveToSuperview
{
    if (self.superview != nil)
    {
        [self reloadImages];
    }
}

- (void)reloadImages
{
    [self.imageBrowserView reloadData];
}

- (UIImage *)imageAtIndex:(NSUInteger)index
{
    CImageBrowserViewCell *cell = (CImageBrowserViewCell *)[self.imageBrowserView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    return cell.image;
}

- (CImageBrowserViewCell *)cellAtIndex:(NSUInteger)index
{
    return (CImageBrowserViewCell *)[self.imageBrowserView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
}

- (void)reloadImageAtIndex:(NSUInteger)index
{
    [self.imageBrowserView reloadItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:index inSection:0]]];
}

- (void)insertImageAtIndex:(NSUInteger)index
{
    [self.imageBrowserView insertItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:index inSection:0]]];
}

- (void)deleteImageAtIndex:(NSUInteger)index
{
    [self.imageBrowserView deleteItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:index inSection:0]]];
    if ([self.imageBrowserView numberOfItemsInSection:0] == 0)
    {
        [self.delegate imageBrowserViewNeedGetBack:self];
    }
    else if (self.curImageIndex == [self.imageBrowserView numberOfItemsInSection:0])
    {
        self.curImageIndex--;
    }
}

#pragma mark - animated show or hide

- (void)showWithAnchorView:(UIView *)anchorView image:(UIImage *)image index:(NSUInteger)index fillStyle:(EImageFillStyle)fillStyle complete:(void (^)())complete
{
    UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
    [self showWithSupperView:shareWindow anchorView:anchorView image:image index:index fillStyle:fillStyle complete:complete];
}

- (void)showWithSupperView:(UIView *)supperView anchorView:(UIView *)anchorView image:(UIImage *)image index:(NSUInteger)index fillStyle:(EImageFillStyle)fillStyle complete:(void (^)())complete
{
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    self.frame = supperView.bounds;
    [supperView addSubview:self];
    self.curImageIndex = index;
    self.imageBrowserView.contentOffset = CGPointMake((self.width)*index, 0);
    if (self.buttonItems.count > 0)
    {
        [self showButtonItemsAnimated:YES complete:^(BOOL finished) {}];
    }
    [self.showView showContentViewForImage:image anchorView:anchorView fillStyle:fillStyle complete:^{
        complete();
    }];
}

- (void)dismissWithAnchorView:(UIView *)anchorView fillStyle:(EImageFillStyle)fillStyle complete:(void (^)())complete
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    if (self.buttonItems.count > 0)
    {
        [self hideButtonItemsAnimated:YES complete:^(BOOL finished) {}];
    }
    CImageBrowserViewCell *cell = (CImageBrowserViewCell *)[self.imageBrowserView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.curImageIndex inSection:0]];
    if (anchorView == nil || cell == nil)
    {
        [UIView animateWithDuration:.25 animations:^{
            self.showView.alpha = 0.0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
            complete();
        }];
    }
    else
    {
        [self.showView dismissContentViewForImage:cell.image anchorView:anchorView fillStyle:fillStyle complete:^{
            [self removeFromSuperview];
            complete();
        }];
    }
}

#pragma mark - scroll view delegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.curImageIndex = scrollView.contentOffset.x / scrollView.width;
    if ([self.delegate respondsToSelector:@selector(imageBrowserView:didMoveToImageAtIndex:)])
        [self.delegate imageBrowserView:self didMoveToImageAtIndex:self.curImageIndex];
}

#pragma mark - collection view datasource and delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.delegate numberOfImagesForImageBrowserView:self];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CImageBrowserViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
    CImageBrowserViewCellInfo *info = [self.delegate imageBrowserView:self cellInfoAtIndex:indexPath.item];
    [cell updateWithCellInfo:info];
    return cell;
}

@end
